﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinFormAssigment.BUS;
using WinFormAssigment.DAO;
using WinFormAssigment.Entities;

namespace WinFormAssigment.GUI
{
    public partial class StudentAttendance : Form
    {

        private List<Student> lstStudents;
        private string classID;
        string tID = Query.userID;
        public StudentAttendance()
        {
            InitializeComponent();
        }

        private void StudentAttendance_Load(object sender, EventArgs e)
        {
            GetAllClassByTeacher(Query.userID);
            lstStudents = DatabaseInteraction.GetAllStudent();
        }

        private void GetAllClassByTeacher(string teacherID)
        {
            TreeNode nodeRoot;
            trvClasses.Nodes.Clear();
            DataTable table = AttendanceManager.GetAllClassIdByTeacher(teacherID);
            foreach (DataRow dr in table.Rows)
            {
                nodeRoot = new TreeNode(dr["ClassID"].ToString().ToUpper());
                trvClasses.Nodes.Add(nodeRoot);
                GetSemester(nodeRoot);
            }
        }

        private static void GetSemester(TreeNode nodeRoot)
        {
            TreeNode nodeParent;
            DataTable table2 = AttendanceManager.GetAllSem();
            foreach (DataRow dr2 in table2.Rows)
            {
                nodeParent = new TreeNode(dr2["Sem"].ToString());
                nodeRoot.Nodes.Add(nodeParent);
                GetSubject(nodeParent, nodeParent.Text);
            }
        }

        private static void GetSubject(TreeNode nodeParent, string sem)
        {
            TreeNode nodeChild;
            DataTable table = AttendanceManager.GetSubjectBySem(sem);
            foreach (DataRow dr in table.Rows)
            {
                nodeChild = new TreeNode(dr["SubjectName"].ToString());
                nodeParent.Nodes.Add(nodeChild);
            }

        }
        public TreeNode Get_Root_Node(TreeNode node)
        {
            if (node.Level > 0)
            {
                node = Get_Root_Node(node.Parent);
            }

            return node;
        }

        private void trvClasses_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = trvClasses.SelectedNode;
            classID = Get_Root_Node(trvClasses.SelectedNode).Text;
            DataTable mytable = AttendanceManager.GetStudentInClass(classID);

            if (mytable != null)
            {
                dgvStudentAttendance.DataSource = mytable;
            }
            if (node.Level == 2)
            {
                FillSessionSubject(e.Node.Text);
                cboSession.SelectedIndex = 0;
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        public void FillStudentInformation(string studentID)
        {
            foreach (Student s in lstStudents)
            {
                if (s.StudentID.Equals(studentID))
                {
                    lblStudentID.Text = s.StudentID;
                    lblStudentName.Text = s.Name;
                    lblGender.Text = s.Gender;
                    lblDOB.Text = s.Dob.ToString();
                    lblEmail.Text = s.Email;
                    lblPhone.Text = s.Phone;
                    lblAdress.Text = s.Address;

                }
            }
        }



        private void FillSessionSubject(string subjectName)
        {
            cboSession.Items.Clear();
            DataTable table = AttendanceManager.GetTotalSessionBySubject(subjectName);
            if (table.Rows.Count > 0)
            {
                foreach (DataRow dr in table.Rows)
                {
                    string s = dr["TotalSession"].ToString();
                    int total = Convert.ToInt16(s);
                    for (int i = 1; i <= total; i++)
                    {
                        if (subjectName.Equals(dr["SubjectName"]))
                        {
                            string s2 = dr["SubjectID"] + "-" + i;
                            cboSession.Items.Add(s2);
                        }
                    }
                }
            }
        }



        private void btnSubmit_Click(object sender, EventArgs e)
        {
            SaveAttendance();
        }

        private void dgvStudentAttendance_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.RowIndex < dgvStudentAttendance.Rows.Count)
            {
                DataGridViewRow row = dgvStudentAttendance.Rows[e.RowIndex];
                string studentID = row.Cells[0].Value.ToString();
                //FillStudentInformation(studentID);
                //MessageBox.Show(studentID);
                foreach (Student s in lstStudents)
                {
                    if (s.StudentID.Equals(studentID))
                    {
                        lblStudentID.Text = s.StudentID;
                        lblStudentName.Text = s.Name;
                        lblGender.Text = s.Gender;
                        lblDOB.Text = s.Dob.ToShortDateString();
                        lblEmail.Text = s.Email;
                        lblPhone.Text = s.Phone;
                        lblAdress.Text = s.Address;

                    }
                }
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            DataTable mytable = AttendanceManager.GetStudentInClass(classID);
            if (mytable != null)
            {
                dgvStudentAttendance.DataSource = mytable;
            }

        }

        private void ckbAllPresent_CheckedChanged(object sender, EventArgs e)
        {

            foreach (DataGridViewRow row in dgvStudentAttendance.Rows)
            {
                if (ckbAllPresent.Checked)
                {
                    ckbAllAbsent.Checked = false;
                    row.Cells["Present"].Value = true;
                    row.Cells["Absent"].Value = false;
                }
                else
                {
                    row.Cells["Present"].Value = false;
                    row.Cells["Absent"].Value = false;
                }
            }


        }

        private void ckbAllAbsent_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dgvStudentAttendance.Rows)
            {
                if (ckbAllAbsent.Checked)
                {
                    ckbAllPresent.Checked = false;
                    row.Cells["Present"].Value = false;
                    row.Cells["Absent"].Value = true;
                }
                else
                {
                    row.Cells["Present"].Value = false;
                    row.Cells["Absent"].Value = false;
                }
            }
        }

        private void SaveAttendance()
        {
            if (cboSession.Text.Equals(""))
            {
                MessageBox.Show("Please choose AttendanceID");
            }
            else
            {
                foreach (DataGridViewRow row in dgvStudentAttendance.Rows)
                {

                    string attendanceID = cboSession.SelectedItem.ToString();
                    string classID = trvClasses.SelectedNode.Parent.Parent.Text;
                    string status = null;
                    string[] s = attendanceID.Split('-');
                    string subjectID = s[0];
                    string timeAttendance = DateTime.Now.ToShortDateString();
                    int sessionCount = Convert.ToUInt16(s[1]);
                    string studentID = Convert.ToString(row.Cells["studentID"].Value);
                    string attendanceDetailID = subjectID + sessionCount + studentID;
                    DataGridViewCheckBoxCell ck = row.Cells[2] as DataGridViewCheckBoxCell;
                    if (Convert.ToBoolean(ck.Value) == true)
                    {
                        status = "Present";
                    }
                    else
                    {
                        status = "Absent";
                    }
                    Attendance att = new Attendance()
                    {
                        AttendanceID = attendanceID,
                        ClassID = classID,
                        TimeAttendance = timeAttendance
                    };
                    AttendanceDetail ad = new AttendanceDetail()
                    {
                        AttendanceDetailID = attendanceDetailID,
                        AttendanceID = attendanceID,
                        StudentID = studentID,
                        SubjectID = subjectID,
                        Status = status,
                        SessionCount = sessionCount
                    };

                    AttendanceManager.InsertAttendance(att, ad);
                }

            }


        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            DataTable table = AttendanceManager.GetAttendanceByID("c1208i", "bdws-1");
            int index = 0;
            foreach (DataRow row in table.Rows)
            {
                dgvStudentAttendance.Rows[index].Cells[0].Value = row["StudentID"].ToString();
                dgvStudentAttendance.Rows[index].Cells[1].Value = row["Name"].ToString();
                string status = row["Status"].ToString();
                if (status == "Present") {
                    dgvStudentAttendance.Rows[index].Cells[2].Value = true;
                    dgvStudentAttendance.Rows[index].Cells[3].Value = false;
                }
                else if (status == "Absent") {
                    dgvStudentAttendance.Rows[index].Cells[2].Value = false;
                    dgvStudentAttendance.Rows[index].Cells[3].Value = true;
                }
                index++;
            }
            dgvStudentAttendance.Invalidate();        
        }

        //private void FillAttendanceByID(string classID, string attendanceID)
        //{
        //    DataTable table = AttendanceManager.GetAttendanceByID(classID, attendanceID);
        //    foreach (DataGridViewRow row in dgvStudentAttendance.Rows)
        //    {
        //        row.Cells["StudentID"].Value = table.Rows["StudentID"].ToString();
        //        row.Cells["Name"].Value = table.Rows["Name"].ToString();
        //        if (table.Rows["Status"] = "Present")
        //        {
        //            row.Cells["Present"].Value = true;
        //            row.Cells["Absent"].Value = false;
        //        }
        //        else if (table.Rows["Status"] = "Absent")
        //        {
        //            row.Cells["Present"].Value = false;
        //            row.Cells["Absent"].Value = true;
        //        }
        //    }
        //}

      
        private void dgvStudentAttendance_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            int index = e.ColumnIndex;
            if (index >= 2 && index <= 3)
            {
                DataGridViewRow row = dgvStudentAttendance.Rows[e.RowIndex];
                DataGridViewCheckBoxCell checkBox = (DataGridViewCheckBoxCell)row.Cells[index];
                if (checkBox.Value != null)
                {
                    bool isChecked = Convert.ToBoolean(checkBox.Value);
                    if (isChecked)
                    {
                        for (int i = 2; i <= 3; i++)
                        {
                            if (i != index)
                            {
                                row.Cells[i].Value = false;
                            }
                        }
                    }
                }
                dgvStudentAttendance.Invalidate();
            }
        }

        private void dgvStudentAttendance_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dgvStudentAttendance.IsCurrentCellDirty)
            {
                dgvStudentAttendance.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            BindingSource bs = new BindingSource();
            bs.DataSource = dgvStudentAttendance.DataSource;
            bs.Filter = "Name like '%" + txtSearch.Text + "%'";
            dgvStudentAttendance.DataSource = bs;
        }
    }
}
